import { getDeptTreeApi } from "@/api/managementCenter/departmentPersonnel";
import { reactive, ref, computed } from "vue";

export default function InitHook() {
  const searchValue = ref<string>("");
  const tableRef = ref<any>(null);
  const searchForm = reactive<Partial<DepartmentPersonnel.SearchForm>>({
    username: undefined,
    roleId: undefined,
    deptId: "0",
    status: undefined,
    pageNum: 1,
    pageSize: 100,
    total: 0
  });
  const departmentOpts = ref<Array<Base.GeneraDataType>>([]);
  const tableData = ref<Array<DepartmentPersonnel.ListRows>>([]);
  const expandedKeys = ref<Array<string | number | undefined | null>>([]);
  const autoExpandParent = ref<boolean>(true);
  const dialogOpts = reactive<Base.DialogOpts>({
    title: "",
    width: "520px",
    component: "",
    type: 1,
    passData: {},
    visible: false
  });
  const drawerOpts = reactive<Base.DrawerOpts>({
    title: "",
    width: "520px",
    component: "",
    type: 1,
    passData: {},
    visible: false
  });
  // 扁平化
  const flattenDepartOpts = computed<Array<Base.GeneraDataType>>(() => {
    const result: Array<Base.GeneraDataType> = [];
    const fn = (array: Array<Base.GeneraDataType>) => {
      for (let i = 0; i < array.length; i++) {
        const target = array[i];
        result.push(target);
        if (target.childList && target.childList.length) fn(target.childList);
      }
    };
    fn(departmentOpts.value);
    return result;
  });
  // 获取嵌套id
  const getParentKey = (key: string | number, tree: Array<Base.GeneraDataType>): string | number | undefined => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.childList) {
        if (node.childList.some((item: any) => item.id === key)) {
          parentKey = node.id;
        } else if (getParentKey(key, node.childList)) {
          parentKey = getParentKey(key, node.childList);
        }
      }
    }
    return parentKey;
  };
  // 获取所有树形数据
  const getDeptTree = () => {
    return getDeptTreeApi().then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        departmentOpts.value = data || [];
        initDepart();
      }
    });
  };
  const initDepart = () => {
    const expanded = flattenDepartOpts.value
      .map((item: Base.GeneraDataType[number]) => {
        if (item.name.indexOf(searchValue.value) > -1) {
          return getParentKey(item.id, departmentOpts.value);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    expandedKeys.value = expanded;
    autoExpandParent.value = true;
  };
  return {
    searchForm,
    tableData,
    searchValue,
    dialogOpts,
    tableRef,
    departmentOpts,
    getDeptTree,
    flattenDepartOpts,
    expandedKeys,
    autoExpandParent,
    getParentKey,
    initDepart,
    drawerOpts
  };
}
